<template>
  <div class="comment-container">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="吐槽开始（最多120字）" maxlength="120" v-model="text"></textarea>
    <mt-button type="primary" size="large" @click="postData">发表评论</mt-button>
    <div class="cmt">
      <div class="cmt-item" v-for="(item,i) in comment" :key="item.id">
        <div class="cmt-title">第{{i+1}}楼：匿名用户 发表时间：{{item.time | dataFormat}}</div>
        <div class="cmt-body">{{item.content}}</div>
      </div>
      <div class="noData" v-show="comment.length==0">暂无数据</div>
    </div>
    <!-- <mt-button type="danger" size="large" plain>加载更多</mt-button> -->
  </div>
</template>
<style lang="less" scoped>
.comment-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 80px;
    margin: 0;
  }
  button {
    margin: 5px 0;
  }
  .cmt {
    line-height: 40px;
    margin: 5px 0;
    font-size: 14px;
    .cmt-title {
      background: #ccc;
      padding-left: 5px;
    }
    .cmt-body {
      text-indent: 2em;
    }
  }
  .noData {
    text-align: center;
    background: #ccc;
  }
}
</style>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      comment: [],
      text: ""
    };
  },
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      this.$http
        .get("comments/" + this.$route.params.id)
        .then(res => {
          console.log(res.body);
          this.comment = res.body.text;
        })
        .catch(err => {
          console.log("请求数据失败");
        });
    },
    postData() {
      if (this.text.trim() == "") {
        Toast("请输入内容");
        this.text = "";
        return;
      }
      if (this.comment == "") {
        var obj = {
          content: this.text.trim(),
          time: new Date()
        };
        this.comment.unshift(obj);
        this.$http
          .post("comments", { id: this.$route.params.id, text: this.comment })
          .then(res => {
            Toast("发表成功");
            this.text = "";
          });
      } else {
        var obj = {
          content: this.text.trim(),
          time: new Date()
        };
        this.comment.unshift(obj);
        this.$http
          .put("comments/" + this.$route.params.id, { text: this.comment })
          .then(res => {
            Toast("发表成功");
            this.text = "";
          });
      }
    }
  }
};
</script>